package com.deductive.web.controller.dynamic;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.deductive.common.core.controller.BaseController;
import com.deductive.common.core.domain.AjaxResult;
import com.deductive.common.core.page.TableDataInfo;
import com.deductive.common.utils.StringUtils;
import com.deductive.domain.special.SpecialTableColumn;
import com.deductive.service.dynamic.IDynamicTableService;
import com.deductive.service.special.SpecialTableColumnService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 动态表通用接口 (支持驼峰-下划线自动转换和空间数据处理)
 */
@Api(tags = "动态表通用接口")
@RestController
@RequestMapping("/dynamic/table")
public class DynamicTableController extends BaseController {

    @Autowired
    private IDynamicTableService dynamicTableService;

    @Autowired
    private SpecialTableColumnService specialTableColumnService;

    @ApiOperation("通用分页查询")
    @PostMapping("/{tableName}/list")
    public TableDataInfo list(
            @ApiParam(value = "要查询的表名", required = true, example = "user_info")
            @PathVariable String tableName,

            @ApiParam(value = "查询参数 (驼峰命名)。\n" +
                    "columns: (可选) 指定返回字段。\n" +
                    "conditions: (可选) 查询条件列表。\n" +
                    "空间查询示例: {\"field\":\"geom\",\"operator\":\"intersects\",\"value\":{\"type\":\"Polygon\",\"coordinates\":[[[120,30],[121,30],[121,31],[120,31],[120,30]]]}}",
                    example = "{\"columns\":[\"userId\",\"userName\"], \"conditions\":[{\"field\":\"userName\",\"operator\":\"like\",\"value\":\"zhang\"}]}")
            @RequestBody(required = false) Map<String, Object> params) {
        startPage();
        List<String> columns = params != null ? (List<String>) params.get("columns") : null;
        List<Map<String, Object>> conditions = params != null ? (List<Map<String, Object>>) params.get("conditions") : null;
        return getDataTable(dynamicTableService.selectPage(tableName, columns, conditions));
    }

    @ApiOperation("查询映射字段名")
    @PostMapping("/{tableName}/queryColumnComment")
    public AjaxResult queryColumnComment(
            @ApiParam(value = "要查询的表名", required = true, example = "user_info")
            @PathVariable String tableName,

            @ApiParam(value = "查询参数 (驼峰命名)。\n" +
                    "columns: (可选) 指定返回字段。\n" +
                    "conditions: (可选) 查询条件列表。\n" +
                    "空间查询示例: {\"field\":\"geom\",\"operator\":\"intersects\",\"value\":{\"type\":\"Polygon\",\"coordinates\":[[[120,30],[121,30],[121,31],[120,31],[120,30]]]}}",
                    example = "{\"columns\":[\"userId\",\"userName\"], \"conditions\":[{\"field\":\"userName\",\"operator\":\"like\",\"value\":\"zhang\"}]}")
            @RequestBody(required = false) Map<String, Object> params) {
        List<String> columns = params != null ? (List<String>) params.get("columns") : null;


        LambdaQueryWrapper<SpecialTableColumn> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(tableName), SpecialTableColumn::getTableName, tableName);
        if (columns != null) {
            queryWrapper.in(SpecialTableColumn::getColumnName, columns);
        }
        List<SpecialTableColumn> list = specialTableColumnService.list(queryWrapper);
        return AjaxResult.success(list);
    }

    @ApiOperation("通用新增")
    @PostMapping("/{tableName}")
    public AjaxResult add(
            @ApiParam(value = "要操作的表名", required = true, example = "user_info")
            @PathVariable String tableName,

            @ApiParam(value = "要插入的数据 (驼峰命名)", required = true, example = "{\"userName\":\"zhangsan\",\"userEmail\":\"zhangsan@example.com\"}")
            @RequestBody Map<String, Object> data) {
        return toAjax(dynamicTableService.insert(tableName, data));
    }

    @ApiOperation("通用修改")
    @PutMapping("/{tableName}")
    public AjaxResult edit(
            @ApiParam(value = "要操作的表名", required = true, example = "user_info")
            @PathVariable String tableName,

            @ApiParam(value = "包含更新数据(data)和更新条件(conditions)的Map (驼峰命名)",
                    required = true,
                    example = "{\"data\":{\"userName\":\"newName\"},\"conditions\":[{\"field\":\"userId\",\"operator\":\"=\",\"value\":1}]}")
            @RequestBody Map<String, Object> params) {

        Map<String, Object> data = (Map<String, Object>) params.get("data");
        List<Map<String, Object>> conditions = (List<Map<String, Object>>) params.get("conditions");
        return toAjax(dynamicTableService.update(tableName, data, conditions));
    }

    @ApiOperation("通用删除")
    @DeleteMapping("/{tableName}")
    public AjaxResult remove(
            @ApiParam(value = "要操作的表名", required = true, example = "user_info")
            @PathVariable String tableName,

            @ApiParam(value = "删除条件列表 (驼峰命名)",
                    required = true,
                    example = "{\"conditions\":[{\"field\":\"userId\",\"operator\":\"=\",\"value\":1}]}")
            @RequestBody Map<String, Object> params) {

        List<Map<String, Object>> conditions = (List<Map<String, Object>>) params.get("conditions");
        return toAjax(dynamicTableService.delete(tableName, conditions));
    }
}
